"""
xiaohongshu_backend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework_simplejwt.views import TokenRefreshView

# FastAPI 集成相关导入
from django.http import HttpResponse
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from asgiref.sync import sync_to_async

# 创建 FastAPI 应用实例
fastapi_app = FastAPI(
    title="Xiaohongshu Recommendations API",
    description="FastAPI endpoints for recommendation system",
    version="1.0.0"
)

# 配置 CORS
fastapi_app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 定义 FastAPI 路由
@fastapi_app.get("/trending")
async def get_trending_notes(request: Request):
    """获取热门笔记推荐"""
    from notes.models import Note
    
    # 使用 sync_to_async 包装 Django ORM 操作
    trending_notes = await sync_to_async(list)(
        Note.objects.filter(is_public=True).order_by('-likes_count')[:20]
    )
    
    # 手动序列化数据
    results = []
    for note in trending_notes:
        results.append({
            "id": note.id,
            "title": note.title,
            "cover_image": note.cover_image.url if note.cover_image else None,
            "author": {
                "id": note.author.id,
                "username": note.author.username,
                "avatar": note.author.avatar.url if note.author.avatar else None
            },
            "likes_count": note.likes_count,
            "created_at": note.created_at.isoformat()
        })
    
    return {"count": len(results), "results": results}

@fastapi_app.get("/personal/{user_id}")
async def get_personal_recommendations(request: Request, user_id: int):
    """获取个性化推荐"""
    # 简化版的个性化推荐逻辑
    # 实际应用中应使用更复杂的算法
    from notes.models import Note, Like
    
    # 获取用户喜欢过的笔记
    user_likes = await sync_to_async(list)(
        Like.objects.filter(user_id=user_id).values_list('note_id', flat=True)
    )
    
    # 获取相关推荐（这里简单地排除用户已点赞的笔记）
    recommended_notes = await sync_to_async(list)(
        Note.objects.filter(
            is_public=True,
            id__not_in=user_likes
        ).order_by('-likes_count')[:20]
    )
    
    # 手动序列化数据
    results = []
    for note in recommended_notes:
        results.append({
            "id": note.id,
            "title": note.title,
            "cover_image": note.cover_image.url if note.cover_image else None,
            "author": {
                "id": note.author.id,
                "username": note.author.username,
                "avatar": note.author.avatar.url if note.author.avatar else None
            },
            "likes_count": note.likes_count,
            "created_at": note.created_at.isoformat()
        })
    
    return {"count": len(results), "results": results}

# Django 视图函数，用于将请求转发给 FastAPI
def fastapi_router(request, path):
    """将 /fastapi/{path} 的请求转发给 FastAPI 应用"""
    import uvicorn
    from starlette.middleware.wsgi import WSGIMiddleware
    
    # 这里使用简单的路径映射
    if path == 'feed/trending':
        from fastapi.responses import Response
        import json
        import asyncio
        
        # 运行 FastAPI 异步视图
        result = asyncio.run(get_trending_notes(request))
        return HttpResponse(
            json.dumps(result),
            content_type="application/json"
        )
    elif path.startswith('feed/personal/'):
        import json
        import asyncio
        
        # 提取 user_id
        user_id = path.split('/')[-1]
        try:
            user_id = int(user_id)
            # 运行 FastAPI 异步视图
            result = asyncio.run(get_personal_recommendations(request, user_id))
            return HttpResponse(
                json.dumps(result),
                content_type="application/json"
            )
        except ValueError:
            return HttpResponse(
                json.dumps({"detail": "Invalid user ID"}),
                status=400,
                content_type="application/json"
            )
    
    return HttpResponse(
        json.dumps({"detail": "Not found"}),
        status=404,
        content_type="application/json"
    )

urlpatterns = [
    path('admin/', admin.site.urls),
    
    # 认证相关路由
    path('api/auth/register/', include('user_auth.urls')),
    path('api/auth/login/', include('user_auth.urls')),
    path('api/auth/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/auth/profile/', include('user_auth.urls')),
    
    # 笔记相关路由
    path('api/notes/', include('notes.urls')),
    
    # 评论相关路由
    path('api/comments/', include('comments.urls')),
    
    # FastAPI 路由
    path('fastapi/<path:path>/', fastapi_router),
]

# 静态文件和媒体文件的路由配置
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# 处理不存在的路由
urlpatterns += [
    path('<path:path>', lambda request, path: HttpResponse(
        json.dumps({"detail": "Not found"}),
        status=404,
        content_type="application/json"
    ))
]